package com.csj.mvvm.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Process
import androidx.appcompat.app.AppCompatDelegate
import com.csj.mvvm.App


object NightModeUtil {
    /**
     * 系统是否是深色模式
     */
    fun getSysNightMode(context: Context): Boolean {
        val uiMode: Int =
            context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
        return uiMode == Configuration.UI_MODE_NIGHT_YES
    }

    /**
     * 当前APP是否是深色模式
     */
    fun isNightMode(context: Context): Boolean {
        return if (getSystemMode()) {
            LogUtil.e("isNightMode getSysNightMode=" + getSysNightMode(context))
            getSysNightMode(context)
        } else {
            LogUtil.e("isNightMode getNightMode=" + getNightMode())
            getNightMode()
        }
    }

    /**
     * 获取是否跟随系统，默认true
     */
    open fun getSystemMode(): Boolean {
        val spBoolean: Boolean by SPreference("KEY_MODE_SYSTEM", false)
        return spBoolean
    }

    fun setSystemMode(nightMode: Boolean) {
        var spBoolean: Boolean by SPreference("KEY_MODE_SYSTEM", false)
        spBoolean = nightMode
    }

    /**
     * 获取是否设置深色模式，默认false
     */
    open fun getNightMode(): Boolean {
        val spBoolean: Boolean by SPreference("KEY_MODE_NIGHT", false)
        return spBoolean
    }

    fun setNightMode(nightMode: Boolean) {
        var spBoolean: Boolean by SPreference("KEY_MODE_NIGHT", false)
        spBoolean = nightMode
    }


    /**
     * 初始化App深色模式
     *
     * @param systemMode 是否是跟随系统
     * @param nightMode  是否是深色模式
     */
    @JvmOverloads
    fun initNightMode(nightMode: Boolean) {
        if (nightMode) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        }
    }

    /**
     * 重启App
     */
    fun restartApp(activity: Activity) {
        val intent: Intent? =
            App.instance.packageManager.getLaunchIntentForPackage(App.instance.packageName)
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
            activity.startActivity(intent)
            Process.killProcess(Process.myPid())
        }
    }

    fun restartApp(activity: Activity, intent: Intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
        activity.startActivity(intent)
        Process.killProcess(Process.myPid())
    }
}